package org.example.db;

import org.example.annotation.Column;
import org.example.annotation.Table;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import static java.sql.DriverManager.getConnection;

/**
 * author:vesper.z
 * date: 2024  18:00
 * class: DBHelper
 * description：
 **/
public class ORMFramework {

    // 保存实体类到数据库
    public static void save(Object obj) throws Exception {
        // 获取实体类的Class对象
        Class<?> clazz = obj.getClass();
        // 获取实体类上的@Table注解
        Table table = clazz.getAnnotation(Table.class);
        if (table == null) {
            throw new RuntimeException("No @Table annotation found on class " + clazz.getName());
        }
        // 获取实体类对应的数据库表名
        String tableName = table.name();

        // 构造SQL语句
        StringBuilder sb = new StringBuilder("insert into ").append(tableName).append("(");
        // 获取实体类的所有属性
        Field[] fields = clazz.getDeclaredFields();
        // 用于存储属性值的列表
        List<Object> values = new ArrayList<>();
        // 遍历属性，获取属性上的@Column注解和属性值
        for (Field field : fields) {
            Column column = field.getAnnotation(Column.class);
            if (column != null) {
                // 获取属性对应的数据库列名
                String columnName = column.name();
                sb.append(columnName).append(",");
                // 设置属性可访问，获取属性值
                field.setAccessible(true);
                Object value = field.get(obj);
                values.add(value);
            }
        }
        // 删除最后一个逗号，并添加values子句
        sb.deleteCharAt(sb.length() - 1).append(") values (");
        // 添加占位符
        for (int i = 0; i < values.size(); i++) {
            sb.append("?").append(",");
        }
        // 删除最后一个逗号，并添加右括号
        sb.deleteCharAt(sb.length() - 1).append(")");
        // 获取数据库连接
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = getConnection();
            if (createTableIfExists(conn, ps) == 0) {
                // 创建PreparedStatement对象，并设置参数
                ps = conn.prepareStatement(sb.toString());
                for (int i = 0; i < values.size(); i++) {
                    ps.setObject(i + 1, values.get(i));
                }
                // 执行SQL语句
                if (ps.executeUpdate() == 1) {
                    System.out.println("数据插入成功！");
                }
            }
        } finally {
            // 关闭数据库连接
            close(conn, ps, null);
        }
    }

    private static int createTableIfExists(Connection conn, PreparedStatement ps) {
        String create = "CREATE TABLE IF NOT EXISTS person (\n" +
                "  id INT(20) NOT NULL AUTO_INCREMENT,\n" +
                "  name VARCHAR(20) NOT NULL,\n" +
                "  age INT(20) NOT NULL,\n" +
                "  PRIMARY KEY (id)\n" +
                ");";
        try {
            ps = conn.prepareStatement(create.toString());
            return ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    // 获取数据库连接
    private static Connection getConnection() throws Exception {
//        String driver = "com.mysql.jdbc.Driver";
        String driver = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/test";
        String user = "root";
        String password = "12345678";
        Class.forName(driver);
        Connection conn = DriverManager.getConnection(url, user, password);
        return conn;
    }

    // 关闭数据库连接
    private static void close(Connection conn, Statement stmt, ResultSet rs) throws Exception {
        if (rs != null) {
            rs.close();
        }
        if (stmt != null) {
            stmt.close();
        }
        if (conn != null) {
            conn.close();
        }
    }


}
